from django.shortcuts import render, get_object_or_404, redirect
from django.db.models import Q,F, ExpressionWrapper, IntegerField
from .models import Category, Post,Tag
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.views.decorators.http import require_http_methods
from .models import Comment
from .forms import CommentForm

def index(request):
    # 查询所有文章，首先按照是否为热门排序（热门文章排在前面），然后按照浏览量排序（浏览量高的排前面）
    post_list = Post.objects.annotate(
        hot_priority=ExpressionWrapper(F('is_hot'), output_field=IntegerField())
    ).order_by('-hot_priority', '-pv')
    # 分页方法，每页显示10篇文章
    paginator = Paginator(post_list, 10)
    # 从GET请求中获取页码，如果没有提供，默认为1
    page_number = request.GET.get('page', 1)
    # 获取当前页的文章对象
    page_obj = paginator.get_page(page_number)

    # 将当前页的对象、所有分类和当前选中的分类传递给模板
    context = {
        'page_obj': page_obj,
    }
    return render(request, 'blog/index.html', context)

def category_list(request, category_id):
    # 获取当前分类
    current_category = get_object_or_404(Category, id=category_id)
    # 获取该分类下的所有文章
    posts = Post.objects.filter(category=current_category).annotate(
        sort_score=ExpressionWrapper(F('is_hot') * F('pv'), output_field=IntegerField())
    ).order_by('-sort_score', '-pv')
    paginator = Paginator(posts, 10)
    page_number = request.GET.get('page', 1)
    page_obj = paginator.get_page(page_number)


    # 将当前分类的 ID 和文章列表传递给模板
    context = {
        'current_category_id': category_id,  # 添加当前分类 ID 到上下文
        'page_obj': page_obj,
        'category': current_category,
    }
    return render(request, 'blog/category_list.html', context)


def post_detail(request, post_id):
    post = get_object_or_404(Post, id=post_id)
    
    # 增加浏览量
    post.pv += 1
    post.save()
    
    prev_post = Post.objects.filter(pub_date__lt=post.pub_date).order_by('-pub_date').first()
    next_post = Post.objects.filter(pub_date__gt=post.pub_date).order_by('pub_date').first()

    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            new_comment = form.save(commit=False)
            new_comment.post = post
            new_comment.user = request.user
            new_comment.save()
            return redirect('blog:post_detail', post_id=post_id)
    else:
        form = CommentForm()

    comments = post.comments.all()

    context = {
        'post': post,
        'prev_post': prev_post,
        'next_post': next_post,
        'form': form,
        'comments': comments,
    }
    return render(request, 'blog/detail.html', context)

@require_http_methods(["GET"])  # 确保只处理 GET 请求
def search(request):
    """ 搜索视图 """
    keyword = request.GET.get('q')
    post_list = Post.objects.none()  # 没有搜索词时默认不显示文章

    if keyword:
        try:
            # 包含查询的方法，用 Q 对象来组合复杂查询
            post_list = Post.objects.filter(
                Q(title__icontains=keyword) | 
                Q(desc__icontains=keyword) | 
                Q(content__icontains=keyword)
            ).distinct()  # 使用 distinct() 避免重复文章
        except Post.DoesNotExist:
            # 如果没有文章匹配搜索词，显示空的文章列表
            post_list = Post.objects.none()

    paginator = Paginator(post_list, 2)  # 每页显示2篇文章
    page_number = request.GET.get('page', 1)
    try:
        page_obj = paginator.get_page(page_number)
    except PageNotAnInteger:
        # 如果页码不是整数，返回第一页
        page_obj = paginator.page(1)
    except EmptyPage:
        # 如果页码超出范围，返回最后一页
        page_obj = paginator.page(paginator.num_pages)

    context = {
        'page_obj': page_obj,
        'keyword': keyword  # 将搜索词传递到模板上下文
    }
    return render(request, 'blog/index.html', context)

def tag_detail(request, tag_id):
    tag = get_object_or_404(Tag, id=tag_id)
    page_obj = tag.posts.all()
    context = {'page_obj': page_obj, 'tag': tag}
    return render(request, 'blog/index.html', context)

